package com.ygk.bluepath.core.Presenter;

import android.content.Intent;

import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.ygk.bluepath.bean.LocationBean;
import com.ygk.bluepath.bean.LocationBeanCache;
import com.ygk.bluepath.core.BPresenter;
import com.ygk.bluepath.core.View.WatchingActivity;
import com.ygk.bluepath.core.View.WatchingView;
import com.ygk.bluepath.service.LBSService;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import utils.DateUtil;
import utils.Inf;
import utils.LocationUtil;
import utils.LogUtils;
import utils.ServiceUtil;

/**
 * Created by Handreace on 2016/7/11.
 */
public class WatchingPresenter extends BPresenter {
    private WatchingActivity wacthingActivity;
    private WatchingView wacthingView;
   // private WatchingModel wacthingModel;


    private List<LocationBeanCache> availableList;//存储有效点的队列
    private int state = 0;//行驶状态，默认0；1预约中未进站；2已进站；3已出站
    private LocationBeanCache startBean = new LocationBeanCache();//起点站
    private LocationBeanCache endBean = new LocationBeanCache();//终点站

    public WatchingPresenter(WatchingActivity activity, WatchingView mView) {
        super(activity, mView);
        this.wacthingActivity = activity;
        this.wacthingView = mView;
        //wacthingModel = new WatchingModel(this);
        //setModel(wacthingModel);
        availableList = new ArrayList<LocationBeanCache>();
    }


    @Override
    public void LBSResult(double longitude, double latitude) {
        super.LBSResult(longitude, latitude);
        wacthingView.lbsResult(longitude, latitude);
        List<LocationBeanCache> mlist = (List<LocationBeanCache>) getLocationBySelector(Selector.from(LocationBeanCache.class) //查询条件
                       /* .and("longitude", ">", longitude - Inf.longitudeWave)
                        .and("longitude", "<", longitude + Inf.longitudeWave)
                        .and("latitude", ">", latitude - Inf.latitudeWave)
                        .and("latitude", "<", latitude + Inf.latitudeWave));*/
                .where(WhereBuilder.b("longitude", ">", longitude - Inf.longitudeWave).and("longitude", "<", longitude + Inf.longitudeWave))
                .and(WhereBuilder.b("latitude", ">", latitude - Inf.latitudeWave).and("latitude", "<", latitude + Inf.latitudeWave)));

        if (mlist != null && mlist.size() > 0) {
            tt(mlist.size() + "条数据匹配");
            for (LocationBeanCache bean : mlist) {
                bean.setRecordTimes(bean.getRecordTimes() + 1);
                saveLocationOrUpdate(LocationUtil.copyLocationBeanCache(bean));
                // tt("update");
                if (state == 1) {//预约状态
                    if (bean.getLocationType() == 0) {
                        startBean = LocationUtil.copyLocationBeanCache(bean);
                        wacthingView.setTips("当前经纬度为（" + longitude + "," + latitude + "),\n已检测到收费站" + bean.getFlagId() + "-(" + bean.getRecordTimes() + ")次-距离" + LocationUtil.getShortDistance(bean.getLongitude(), bean.getLatitude(), longitude, latitude) + "米,是否设置为入口？");
                    }

                } else if (state == 2) {//进站状态
                    if (bean.getLocationType() == 0) {
                        endBean = LocationUtil.copyLocationBeanCache(bean);
                        wacthingView.setTips("当前经纬度为（" + longitude + "," + latitude + "),\n已检测到收费站" + bean.getFlagId() + "-(" + bean.getRecordTimes() + ")次-距离" + LocationUtil.getShortDistance(bean.getLongitude(), bean.getLatitude(), longitude, latitude) + "米,是否设置为出口？");
                    } else if (bean.getLocationType() == 1) {
                        wacthingView.setTips("当前经纬度为（" + longitude + "," + latitude + "),\n已检测到标识点" + bean.getFlagId() + "-(" + bean.getRecordTimes() + ")次-距离" + LocationUtil.getShortDistance(bean.getLongitude(), bean.getLatitude(), longitude, latitude) + "米");
                        if (bean.getRecordTimes() >= 3) {//默认是0，第3次有效
                            if (!isExitInAvailableList(bean)) {
                                availableList.add(LocationUtil.copyLocationBeanCache(bean));
                                startReport();//途经点报点
                            }
                            ;
                        }
                        freshView();
                    }

                }

            }

        } else {
            wacthingView.setTips("当前经纬度为（" + longitude + "," + latitude + "),\n未检测到任何标识点与站点");
        }


        LogUtils.i("\n手机自带GPS定位结果：" + "\n\t经度:" + longitude + "\n\t纬度:" + latitude);
    }

    @Override
    public void dealJsonObject(JSONObject result, String oid, Object extraStr) {
        super.dealJsonObject(result, oid, extraStr);
        if (result != null) {
            String msg = result.optString("msg");
            tt(msg);
            int code = result.optInt("code");
            if (code == 0) {
                JSONObject jsonData = result.optJSONObject("data");
                if (jsonData != null) {
                    if (oid.equals("pointReport")) {
                        String status = jsonData.optString("status");
                        tt("status:" + status);
                    }

                }
            }

        }

    }

    public void appoint() {
        state = 1;
        deleteAll(LocationBeanCache.class);
        List<LocationBean> mlist = (List<LocationBean>) getLocationAll(LocationBean.class);
        if (mlist != null && mlist.size() > 0) {
            for (LocationBean lb : mlist) {
                saveLocationCache(LocationUtil.copyLocationBeanCache(lb));
            }
        } else {
            tt("本地数据库初始化失败");
        }

        //开启定位
        if (ServiceUtil.isServiceWork(activity, "com.ygk.bluepath.service.LBSService")) {
            LogUtils.e("com.ygk.bluepath.service.LBSService is running");
        } else {
            LogUtils.e("com.ygk.bluepath.service.LBSService is dead");
            startService();
        }
        LogUtils.logToFile(DateUtil.getDateString() + ":开始预约", true);
        tt("成功预约");
    }

    public void reset() {
        state = 0;
        availableList.clear();
        startBean = new LocationBeanCache();//起点站
        endBean = new LocationBeanCache();//终点站
        stopService();
    }

    public void startService() {

        Intent i = new Intent(activity, LBSService.class);
        activity.startService(i);
        LogUtils.i("in startService method.");

    }

    public void stopService() {

        Intent i = new Intent(activity, LBSService.class);
        activity.stopService(i);
        LogUtils.i("in stopService method.");

    }

    private boolean isExitInAvailableList(LocationBeanCache lbBean) {
        for (LocationBeanCache avaBean : availableList) {
            if (avaBean.getFlagId().equals(lbBean.getFlagId())) {
                return true;
            }
        }
        return false;
    }

    private void startReport() {
        String reportString = "";

        if (!startBean.getFlagId().isEmpty()) {
            reportString += startBean.getFlagId() + "--";
        }

        for (LocationBeanCache lb : availableList) {
            reportString += lb.getFlagId() + "--";
        }
        if (!endBean.getFlagId().isEmpty()) {
            reportString += endBean.getFlagId();
        }

        LogUtils.logToFile(DateUtil.getDateString() + ":上报点\n" + reportString, true);

        activity.bMap.put("token", sp.getToken());
        activity.bMap.put("point_id", reportString);
        doPost("car/pointReport", activity.bMap, true, false, "pointReport", "");

    }

    private void freshView() {

        switch (state) {//行驶状态，默认0；1预约中未进站；2已进站；3已出站
            case 0:

                break;
            case 1:
               /* for (LocationBeanCache locationBeanCache:availableList){
                    if (locationBeanCache.getLocationType()==0){
                        startBean= LocationUtil.copyLocationBeanCache(locationBeanCache);
                        tv_in.setText(startBean.getFlagId()+"——("+startBean.getLongitude()+","+startBean.getLatitude()+")——"+startBean.getRecordTimes()+"次");
                    }
                }*/
                break;
            case 2:

                String throughString = "";

                for (LocationBeanCache locationBeanCache : availableList) {

                    if (locationBeanCache.getLocationType() == 1) {

                        throughString += locationBeanCache.getFlagId() + "(" + locationBeanCache.getRecordTimes() + ")次——";
                    }
                }
                wacthingView.setTextThrough(throughString);

                break;
            case 3:

                break;

        }

    }

    public void driveOut() {
        if (endBean.getFlagId().equals("")) {
            tt("暂未检测到出口");
            return;
        }
        wacthingView.setTextOut(endBean.getFlagId() + "——(" + endBean.getLongitude() + "," + endBean.getLatitude() + ")——" + endBean.getRecordTimes() + "次");


        state = 3;//行驶状态，默认0；1预约中未进站；2已进站；3已出站

        LogUtils.logToFile(DateUtil.getDateString() + ":已出站", true);
        stopService();
        startReport();//出口报点
    }

    public void driveIn() {
        if (startBean.getFlagId().equals("")) {
            tt("暂未检测到入口");
            return;
        }
        wacthingView.setTextIn(startBean.getFlagId() + "——(" + startBean.getLongitude() + "," + startBean.getLatitude() + ")——" + startBean.getRecordTimes() + "次");


        state = 2;//行驶状态，默认0；1预约中未进站；2已进站；3已出站

        LogUtils.logToFile(DateUtil.getDateString() + ":已进站", true);
        startReport();//进口报点
    }
}
